package com.springdoor.wx.api.service.impl;

import com.springdoor.wx.api.entity.ResultConfig;
import com.springdoor.wx.api.entity.SprdGoodsBuyCart;
import com.springdoor.wx.api.mapper.SprdGoodsBuyCartMapper;
import com.springdoor.wx.api.mapper.SprdGoodsConfigMapper;
import com.springdoor.wx.api.service.SprdGoodsBuyCartService;
import com.springdoor.wx.utils.string.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SprdGoodsBuyCartServiceImpl implements SprdGoodsBuyCartService {

    @Autowired
    private SprdGoodsBuyCartMapper buyCartMapper;

    @Autowired
    private SprdGoodsConfigMapper goodsConfigMapper;

    @Override
    public Map<String, Object> findListByUserId(Long userId) {
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> buyCartList = buyCartMapper.findListByUserId(userId);
        if (buyCartList == null || buyCartList.size() == 0) {
            result.put("isNotEmpty", false);
            result.put("storeGoods", new ArrayList<>());
            result.put("invalidGoodItems", new ArrayList<>());
            return result;
        } else {
            Map<String, Object> storeMap = new HashMap<>();
            boolean isAllSelected = true;
            Long selectedGoodsCount = 0l;
            Long totalAmount = 0l;
            Long totalDiscountAmount = 0l;

            for (Map<String, Object> buyCart : buyCartList) {
                String storeId = buyCart.get("storeId").toString();
                String spuId = (String) buyCart.get("spuId");
                String assort = (String) buyCart.get("assort");
                String isSelected = (String) buyCart.get("isSelected");
                Long quantity = Long.valueOf(buyCart.get("quantity").toString());
                Long price = Long.valueOf(buyCart.get("price").toString());
                Long stockQuantity = Long.valueOf(buyCart.get("stockQuantity").toString());
                Map<String, Object> storeInfo = new HashMap<>();
                List<Map<String, Object>> promotionGoodsList = new ArrayList<>();
                Map<String, Object> promotionGoods = new HashMap<>();
                List<Map<String, Object>> goodsPromotionList = new ArrayList<>();
                boolean isNotFirst = true;
                if (storeMap.containsKey(storeId)) {
                    storeInfo = (Map<String, Object>) storeMap.get(storeId);
                    promotionGoodsList = (List<Map<String, Object>>) storeInfo.get("promotionGoodsList");
                    goodsPromotionList = (List<Map<String, Object>>) promotionGoodsList.get(0).get("goodsPromotionList");
                } else {
                    isNotFirst = false;
                    storeInfo.put("storeId", storeId);
                    storeInfo.put("storeName", buyCart.get("storeName"));
                    storeInfo.put("storeStatus", buyCart.get("shopStatus"));
                    storeInfo.put("lastJoinTime", buyCart.get("joinCartTime"));
                    storeInfo.put("totalDiscountSalePrice", quantity * price);
//                    storeInfo.put("promotionGoodsList", storeId);
//                    storeInfo.put("postageFreePromotionVo", storeId);
                    // 非折扣商品
                    promotionGoods.put("promotionCode", "EMPTY_PROMOTION");
                    promotionGoods.put("isNeedAddOnShop", 0);
                    // 可享折扣商品
//                    promotionGoods.put("title", "满减满折回归");
//                    promotionGoods.put("promotionCode", "MERCHANT");
//                    promotionGoods.put("promotionSubCode", "MYJ");
//                    promotionGoods.put("promotionId", "159174555838121985");
//                    promotionGoods.put("tagText", ["满100元减99.9元"]);
//                    promotionGoods.put("promotionStatus", 3);
//                    promotionGoods.put("tag", "满减");
//                    promotionGoods.put("description", "满100元减99.9元,已减99.9元");
//                    promotionGoods.put("doorSillRemain", null);
//                    promotionGoods.put("isNeedAddOnShop", 0);
                    promotionGoodsList.add(promotionGoods);
                }
                if (StringUtils.equals("1", isSelected)) {
                    selectedGoodsCount += quantity;
                    totalAmount += quantity * price;
                } else {
                    isAllSelected = false;
                }
                Map<String, Object> goodsPromotion = new HashMap<>();
                goodsPromotion.put("uid", buyCart.get("skuId"));
                goodsPromotion.put("saasId", buyCart.get("cartId"));
                goodsPromotion.put("storeId", storeId);
                goodsPromotion.put("spuId", buyCart.get("spuId"));
                goodsPromotion.put("skuId", buyCart.get("skuId"));
                goodsPromotion.put("isSelected", StringUtils.equals("1", isSelected));
                goodsPromotion.put("thumb", buyCart.get("thumb"));
                goodsPromotion.put("title", buyCart.get("title"));
                goodsPromotion.put("primaryImage", buyCart.get("thumb"));
                goodsPromotion.put("quantity", quantity);

                String status = (String) buyCart.get("shopStatus");
                if (StringUtils.equals("2", status) || StringUtils.equals("3", status)) {
                    goodsPromotion.put("stockStatus", false);
                } else if (stockQuantity == 0) {
                    goodsPromotion.put("stockStatus", false);
                } else {
                    goodsPromotion.put("stockStatus", true);

                }
                goodsPromotion.put("stockQuantity", buyCart.get("stockQuantity"));
                goodsPromotion.put("price", buyCart.get("price"));
                goodsPromotion.put("originPrice", buyCart.get("originPrice"));
                goodsPromotion.put("joinCartTime", buyCart.get("joinCartTime"));
                goodsPromotion.put("putOnSale", buyCart.get("putOnSale"));
                List<Map<String, String>> specInfo = new ArrayList<>();
                if (StringUtils.isNotBlank(assort)) {
                    List<ResultConfig> resultConfigs = goodsConfigMapper.fetchAssortConfigByGNumber(spuId, assort.split(","));
                    if (resultConfigs != null && resultConfigs.size() > 0) {
                        resultConfigs.forEach(config -> {
                            Map<String, String> goodsConfig = new HashMap<>();
                            goodsConfig.put("specTitle", config.getConfigName());
                            goodsConfig.put("specValue",
                                    StringUtils.isEmpty(config.getValueName())?config.getConfigName():config.getValueName());
                            specInfo.add(goodsConfig);
                        });
                    }
                }
                if (isNotFirst) {
//                    storeInfo.put("lastJoinTime", buyCart.get("joinCartTime"));
//                    storeInfo.put("totalDiscountSalePrice", storeId);
                }
//
                goodsPromotion.put("specInfo", specInfo);
                goodsPromotionList.add(goodsPromotion);
                promotionGoods.put("goodsPromotionList", goodsPromotionList);
                storeInfo.put("promotionGoodsList", promotionGoodsList);

                storeMap.put(storeId, storeInfo);
            }
            ArrayList<Object> storeList = new ArrayList<>(storeMap.values());
            result.put("storeGoods", storeList);
            result.put("invalidGoodItems", new ArrayList<>());
            result.put("isNotEmpty", true);
            result.put("isAllSelected", isAllSelected);
            result.put("selectedGoodsCount", selectedGoodsCount);
            result.put("totalAmount", totalAmount);
            result.put("totalDiscountAmount", totalDiscountAmount);
            System.out.println(result);
            return result;
        }
    }

    @Override
    public Integer findBuyCartNum(Long userId) {
        return buyCartMapper.findBuyCartNum(userId);
    }

    @Override
    public int insertSprdGoodsBuyCart(SprdGoodsBuyCart sprdGoodsBuyCart) {
        SprdGoodsBuyCart cart = buyCartMapper.findCartBySkuId(sprdGoodsBuyCart);
        if (cart == null) {
            return buyCartMapper.insertSprdGoodsBuyCart(sprdGoodsBuyCart);
        } else {
            cart.setQuantity(cart.getQuantity() + sprdGoodsBuyCart.getQuantity());
            cart.setRemark("重复新增，数量增加：" + sprdGoodsBuyCart.getQuantity());
            return buyCartMapper.updateSprdGoodsBuyCart(cart);
        }
    }

    @Override
    public int updateSprdGoodsBuyCart(SprdGoodsBuyCart sprdGoodsBuyCart) {
        SprdGoodsBuyCart cart = buyCartMapper.findCartBySkuId(sprdGoodsBuyCart);
        if (cart == null) {
            SprdGoodsBuyCart delCart = new SprdGoodsBuyCart();
            delCart.setCartId(sprdGoodsBuyCart.getCartId());
            delCart.setUpdateBy(sprdGoodsBuyCart.getUpdateBy());
            delCart.setDelFlag("1");
            delCart.setRemark("购物车商品SkuId修改为：" + sprdGoodsBuyCart.getSkuId());
            buyCartMapper.removeBuyCartBuCartId(delCart);
            return buyCartMapper.insertSprdGoodsBuyCart(sprdGoodsBuyCart);
        } else if (sprdGoodsBuyCart.getCartId() == cart.getCartId()) {
            SprdGoodsBuyCart updCart = new SprdGoodsBuyCart();
            updCart.setUserId(sprdGoodsBuyCart.getUserId());
            updCart.setSkuId(sprdGoodsBuyCart.getSkuId());
            updCart.setUpdateBy(sprdGoodsBuyCart.getUpdateBy());
            updCart.setQuantity(cart.getQuantity() + sprdGoodsBuyCart.getQuantity());
            updCart.setRemark("购物车数量追加：" + sprdGoodsBuyCart.getQuantity());
            return buyCartMapper.updateSprdGoodsBuyCart(sprdGoodsBuyCart);
        } else {
            SprdGoodsBuyCart delCart = new SprdGoodsBuyCart();
            delCart.setCartId(sprdGoodsBuyCart.getCartId());
            delCart.setUpdateBy(sprdGoodsBuyCart.getUpdateBy());
            delCart.setDelFlag("1");
            delCart.setRemark("购物车商品SkuId修改为：" + sprdGoodsBuyCart.getSkuId());
            buyCartMapper.removeBuyCartBuCartId(delCart);
            sprdGoodsBuyCart.setQuantity(cart.getQuantity() + sprdGoodsBuyCart.getQuantity());
            return buyCartMapper.updateSprdGoodsBuyCart(sprdGoodsBuyCart);
        }
    }

    @Override
    public int updateBuyCartStatus(SprdGoodsBuyCart sprdGoodsBuyCart) {
        return buyCartMapper.updateSprdGoodsBuyCart(sprdGoodsBuyCart);
    }

    @Override
    public int deleteSprdGoodsBuyCartByUserId(Long userId) {
        return buyCartMapper.deleteSprdGoodsBuyCartByUserId(userId);
    }

    @Override
    public int updateStoreSelStatus(SprdGoodsBuyCart sprdGoodsBuyCart) {
        return buyCartMapper.updateStoreSelStatus(sprdGoodsBuyCart);
    }

    @Override
    public int updateGoodsSelStatus(SprdGoodsBuyCart sprdGoodsBuyCart) {
        return buyCartMapper.updateGoodsSelStatus(sprdGoodsBuyCart);
    }

    @Override
    public int updateAllGoodsSelStatus(SprdGoodsBuyCart sprdGoodsBuyCart) {
        return buyCartMapper.updateAllGoodsSelStatus(sprdGoodsBuyCart);
    }

    @Override
    public int updateGoodsQuantity(SprdGoodsBuyCart sprdGoodsBuyCart) {
        return buyCartMapper.updateGoodsQuantity(sprdGoodsBuyCart);
    }
}
